import { useKline } from "@/stores/kline";
import { customStyle } from "./customStyle";
import { useIndicator } from "@/stores/indicator";
import { useSwitch } from "@/stores/switchBox";
import { URL_BUY_EQUITY, URL_BUY_EQUITY_HOME, URL_CAPITAL_EQUITY, URL_CAPITAL_EQUITY_HOME } from "@/comm/api";
import { get } from "@/comm/request";
import { initChartConfig } from "@/components/chart/config";
import {
    Bus,
    CHART_KLINE_SUBSCRIBE,
    CHART_KLINE_SUBSCRIBE_TIME,
    CHART_KLINE__ITEM,
    CHART_KLINE__LIST,
    CONN_BIG_AMOUNT,
    CONN_FLUCTUATION,
    CONN_SIGNAL,
    CONN_STABLE_CURRENCY,
    CONN_STABLE_EVENT,
    INDICATOR_FUNDS,
    INDICATOR_TOGGLE,
    SWITCH_TOGGLE,
    INDICATOR_TREND,
    INDICATOR_WAVE,
    KLINE_CLEAR,
    KLINE_RESET,
    KLINE_RESET_PRICE
} from "@/connetion/Bus";
import { useSignal } from "@/stores/signal";
import { useActivity } from "@/stores/activity";
import { ref, watch, reactive } from "vue";
import { createWaveIndicator, removeWaveIndicator, createFundRateIndicator, removeFundRateIndicator, addCloseBtn } from "./config";
import i18n from "@/locals";
import { debounce, getFixNum, maskHash } from "@/comm/tooler";
import { formatBigNumber, formatTimestamp } from "@/comm/format";
import { getNearData, getNearTime, getTimer } from "./core/tooler";
import { useRoute } from "vue-router";
import { useAction } from "@/stores/action";
import { useVols } from "@/stores/vols";
import { useLayout } from "@/stores/layout";
const { init, registerOverlay, registerFigure, getFigureClass, getSupportedFigures, dispose } = (window as any)["klinecharts"];

export const useComm = function (cid: string, move: any, clickEvent: Function, newspot: any) {
    const kline = useKline();
    const indicator = useIndicator();
    const switchStore = useSwitch();
    const signal = useSignal();
    const activity = useActivity();
    const loading = ref(false);
    const route = useRoute();
    const action = useAction();
    const infoId = ref("");
    const vols = useVols();
    const layout = useLayout()

    let chart: any;
    const overlays: any[] = [];
    // let openIndicator: any[]=[]
    let initMainIndicator: any[] = [];
    let initSubIndicator: any[] = [];
    let initSwitch: any[] = [];

    const toolTips = ref<any[]>([]);
    let changeTimers: any[] = [];
    let eventList: any[] = [];
    let eventMap: any = {};
    let showMoveBtn = ref(true);
    const infoViewData = reactive({ x: 0, y: 0, opacity: 1 });
    let buSellFlag = true;

    watch(
        () => activity.bigAmounts,
        (newVal: any[], oldVal: any[]) => {
            if (oldVal.length == 0 && newVal.length > 0) {
                let tid = setTimeout(() => {
                    if (chart) {
                        newVal.forEach((i: any) => {
                            // addMark(chart, i, true);
                        });
                    }
                }, 300);
                changeTimers.push(tid);
            }
        }
    );

    function calcFix() {
        let pd = 2;
        let obj = kline.list[0];
        let last = getFixNum(kline.curCoin.lastPrice);
        if (obj) {
            let t1 = getFixNum(obj.open);
            let t2 = getFixNum(obj.close);
            let t3 = getFixNum(obj.high);
            let t4 = getFixNum(obj.low);
            let t5 = getFixNum(kline.curCoin.lastPrice);
            pd = Math.max(t1, t2, t3, t4, t5, last, kline.curCoin.priceDisplayDp, 2);
        }
        else {
            pd = Math.max(kline.curCoin.priceDisplayDp, last, 2);
        }
        chart.setPriceVolumePrecision(pd, 3);
    }

    function flitterVolumePrecision(klist: any[]) {
        // console.log('主页klist########################', klist)
        if (klist.length == 0) return;
        let minPrecision = Number(klist[0].close);
        //查找出最小的精度位
        for (let i = 0; i < klist.length; i++) {
            // 可能包含科学计数法所以在这里转换数字
            const value = Number(klist[i].close + "");
            if (value < minPrecision) {
                minPrecision = value;
            }
        }
        const countZeros = (num: number) => {
            const sciNotation = num.toExponential();
            const match = sciNotation.match(/e\+?(-?\d+)/i);
            const exponent = match ? parseInt(match[1]) : 0;
            return Math.abs(exponent);
        };
        // const precision = countZeros(minPrecision)
        let precision = (minPrecision + "").toString().split(".").pop()?.length || 3;
        // console.log("####最小精度位=======>", precision);
        //如果小于3位就给予默认3位
        if (precision < 3) {
            // chart.setPriceVolumePrecision(3, 3);
            precision = 3;
        } else if (precision > 3 && precision < 6) {
            precision = precision + 3;
            // chart.setPriceVolumePrecision(precision + 3, 3);
        } else {
            // precision + 3
            //如果大于3位就给予最小精度位
            // chart.setPriceVolumePrecision(precision, 3);
        }
        kline.changePriceLen(precision);
        chart.setPriceVolumePrecision(precision, 3);
    }

    async function start() {
        // console.log("jsz ##########", "init chart", cid);
        // kline.list.forEach(i=>console.log("----", getTimer(i.timestamp)));

        // if (!kline.map.length) {
        //     await kline.init();
        //     kline.changeCurCoin(kline.map[0]);
        // }

        eventMap = {};
        let item: any;

        overlays.splice(0);
        eventList = [];
        console.log("清空");
        chart = init(cid, {});
        console.log("清空清空清空清空清空", chart);
        chart.setStyles(customStyle);
        chart.setMaxOffsetLeftDistance(1400);
        chart.setMaxOffsetRightDistance(1400);
        initMainIndicator = indicator.getMainOpen();
        initSwitch = switchStore.getSwitch();
        // console.log(initMainIndicator,"为什么不显示")
        let candleType = kline.curInterval.name == "S1" ? "area" : "candle_solid";
        (window as any).candleType = candleType;
        chart.setStyles({
            candle: {
                type: candleType
            }
        });
        chart.setStyles({
            grid: { show: false }
        });
        if (kline.curInterval.name == "S1") {
            initSubIndicator.map(item => {
                item.selected = false;
            });
        }

        // customStyle.candle.type = candleType;
        // chart.setStyles(customStyle);
        // setTimeout(() => {
        //     addInfo(infoViewData);
        // }, 3000);
        // addInfo(infoViewData);

        // addHistoryEvent();

        addEventListener();
        // console.log(initMainIndicator, "stststststs");

        // indicator.clearSelected();

        // chart.setPriceVolumePrecision(kline.curCoin.priceDisplayDp, kline.curCoin.priceDisplayDp);

        // setTimeout(()=>{
        //     chart.zoomAtDataIndex(10, 0);
        // }, 3000)

        if (kline.curInterval.name !== "S1") {
            initSubIndicator.map(item => {
                Bus.emit(INDICATOR_TOGGLE, item);
            });
            // updateBuySell(true);

            // item = indicator.getByValue("CHAIN_BUY");
            // if (item) {
            //     item.selected = true;
            //     Bus.emit(INDICATOR_TOGGLE, item);
            // }
            // item = indicator.getByValue("CHAIN_SELL");
            // if (item) {
            //     item.selected = true;
            //     Bus.emit(INDICATOR_TOGGLE, item);
            // }

            // if (route.name == "home") {
            //     console.log("home");
            // }

            // item = indicator.getByValue("EMA");
            // if (item) {
            //     item.selected = true;
            //     Bus.emit(INDICATOR_TOGGLE, item);
            // }

            item = indicator.getSubByValue("VOL");
            if (!item.selected) {
                item.selected = true;
                Bus.emit(INDICATOR_TOGGLE, item);
            }
        }
        // 大额转账交易
        activity.getEventRange(kline.curCoin.tokenAddress).forEach((i: any) => {
            // addMark(chart, i);
        });

        activity.bigAmounts.forEach((i: any) => {
            // addMark(chart, i);
        });

        //设置数据
        chart.applyNewData(kline.list);
        // chart.setOffsetRightDistance(20)

        if (kline.list.length > 0) {
            chart.zoomAtTimestamp(1.5, kline.list[kline.list.length - 1].timestamp, 400);
        }
        layout.toggleChartsLoading(false)
        initSwitch.map(item => {
            item.selected = true;
            Bus.emit(SWITCH_TOGGLE, item);
        });
        console.log(initSwitch);
        initMainIndicator.map(item => {
            Bus.emit(INDICATOR_TOGGLE, item);
        });

        // console.log("##jsz 设置数据,问题数据书书书书书书书", kline.list);
        //    kline.list.map((item=>{
        //     console.log(new Date(item.timestamp))
        // }))
        // chart.createIndicator('TEST-Render', true, { id: 'candle_pane' });
        // chart.createIndicator(
        //     {
        //         name: "HBAR",
        //         calc: function (dataList: any[], indicator: any) {
        //             return dataList;
        //         },
        //         draw: (param: any) => {
        //             const { ctx, visibleRange, yAxis, bounding, indicator, kLineDataList } = param;
        //             // console.log(param);
        //             let max = 0;
        //             let min = Number.MAX_VALUE;
        //             const result = indicator.result;
        //             for (let i = visibleRange.realFrom; i < visibleRange.to; i++) {
        //                 // max = Math.max(max, result[i].volume);
        //                 max = Math.max(max, result[i].high);
        //                 min = Math.min(min, result[i].low);
        //             }

        //             let hpx = 30;
        //             let y1 = yAxis.convertToPixel(max);
        //             let y2 = yAxis.convertToPixel(min);
        //             let count = Math.abs(y1 - y2) / hpx;
        //             // console.log("count", count, visibleRange.realFrom, visibleRange.to)

        //             let ary = calcVRVP(kLineDataList.slice(visibleRange.realFrom, visibleRange.to), count);
        //             // console.log(ary);
        //             const maxLen = Math.max(...ary.map(i => i.t));
        //             const maxP = Math.max(...ary.map(i => i.p));
        //             const minP = Math.min(...ary.filter(i=>i.p>0).map(i => i.p));
        //             // console.log("maxLen", maxLen)

        //             const length = visibleRange.to - visibleRange.from;
        //             const barHeight = bounding.height / length;
        //             // const realBarHeight = barHeight * 0.8;
        //             ctx.fillStyle = "rgba(0, 20, 255, .8)";
        //             // let startY = (barHeight - realBarHeight) / 2;
        //             // for (let i = visibleRange.from; i < visibleRange.to; i++) {
        //             //     const barWidth = Math.floor(result[i].volume / max * 150)
        //             //     ctx.fillRect(bounding.width - barWidth, startY, barWidth, realBarHeight);
        //             //     startY += barHeight
        //             // }
        //             // console.warn("ary", ary)
        //             let startY = 0;
        //             // let realBarHeight = bounding.height / ary.length;
        //             let p1 = yAxis.convertToPixel(maxP);
        //             let p2 = yAxis.convertToPixel(minP);
        //             // let realBarHeight = (p2 - p1) / ary.length;
        //             let realBarHeight = hpx * 0.96;
        //             // console.log("realBarHeight", realBarHeight)
        //             let aim:any[] = [];
        //             for (let i = 0, len = ary.length; i < len; i++) {
        //                 const barWidth = (ary[i].t / maxLen) * 200;
        //                 let y = yAxis.convertToPixel(ary[i].p);
        //                 // ctx.fillRect(bounding.width - barWidth, y, barWidth, realBarHeight * 0.9);
        //                 // startY += realBarHeight;
        //                 aim.push({
        //                     w: barWidth,
        //                     h: realBarHeight,
        //                     x: bounding.width - barWidth,
        //                     y: y,
        //                     ...ary[i]

        //                 })
        //             }
        //             vols.changeVols(aim);
        //             vols.changeVisible(true);
        //             return false;
        //         }
        //     },
        //     true,
        //     { id: "candle_pane" }
        // );

        // flitterVolumePrecision(kline.list);
        calcFix();
        // chart.setPriceVolumePrecision(calcFix(), 3);
        // chart.setPriceVolumePrecision(kline.curCoin.sizeDisplayDp, 3);

        if (kline.curInterval.name !== "S1") {
            chart.loadMore(async (t: any) => {
                console.warn("more startTime, 加载更多");
                // console.log("more startTime", t);
                let limit = 1500; //测试-----------------------------------------------------------
                let res: any = chart.getDataList();
                // console.log(res.length, "图上数据长度")
                if (res.length > 10000) {
                    return;
                }
                if (res.length < 1000) {
                    console.log("没有更多");
                    return;
                }
                const list = await kline.loadMore(res[0].timestamp, limit);
                console.log("load history", list);
                const hasNext = list.length == limit;
                let temp = [...list];
                if (list && list.length) {
                    if(list[list.length - 1].startTime == res[0].startTime){
                        console.warn("重合数据");
                        temp = temp.slice(0, -1);
                    }
                    // temp = temp.slice(0, -1);
                }

                chart.applyMoreData(temp, hasNext, async (t: any) => {
                    // console.log("添加历史记录完成")
                    // console.log(res.length, "应该变化的 图上数据长度");
                    let temp1 = indicator.getSubByValue("CHAIN_SELL");
                    let temp2 = indicator.getSubByValue("CHAIN_BUY");
                    if (temp1?.selected || temp2?.selected) {
                        loadMoreBuySell(list[0].timestamp, list[list.length - 1].timestamp, list.length);
                    }
                });

                initSwitch = switchStore.getSwitch();

                console.log(initSwitch, "swswswswswswswswssw");

                initSwitch.map(item => {
                    item.selected = true;
                    Bus.emit(SWITCH_TOGGLE, item);
                });
            });
        }

        activity.loadHistory(kline.curCoin.tokenAddress).then(() => {
            // console.log("加载历史记录", res);
            // addHistoryEvent();
        });

        if (kline.curInterval.name !== "S1") {
            //买入卖出信号
            // signal.loadHistory(kline.curCoin.symbol, kline.curInterval.name).then(() => {
            //     signal.list.forEach((i: any) => {
            //         let id = addSignalBS(i);
            //         overlays.push(id);
            //     });
            // });
        }

        // action.loadData(kline.curCoin.tokenAddress, kline.list[0].timestamp, kline.list[kline.list.length - 1].timestamp).then(res=>{

        // })

        // let tid = setTimeout(() => {
        //     let list = chart.getDataList();
        //     addEvent(list[list.length - 20]);
        // }, 4000);
        // changeTimers.push(tid);
    }

    function checkBSIdx(loaded: boolean) {
        let item;
        if (loaded) {
            item = indicator.getByValue("CHAIN_BUY");
            if (item) {
                item.selected = true;
                Bus.emit(INDICATOR_TOGGLE, item);
            }

            item = indicator.getByValue("CHAIN_SELL");
            if (item) {
                item.selected = true;
                Bus.emit(INDICATOR_TOGGLE, item);
            }

            // item = indicator.getByValue("SELL");
            // if (item) {
            //     item.selected = true;
            //     Bus.emit(INDICATOR_TOGGLE, item);
            // }
            // item = indicator.getByValue("BUY");
            // if (item) {
            //     item.selected = true;
            //     Bus.emit(INDICATOR_TOGGLE, item);
            // }
        } else {
            item = indicator.getSubByValue("VOL");
            if (item) {
                item.selected = true;
                Bus.emit(INDICATOR_TOGGLE, item);
            }
        }
    }

    function addEvent(aim: any, removeId?: string) {
        let flag = true;
        let item = getNearData(eventList, aim);
        // console.log(aim, eventList, "这是正常的list",removeId,"indexxxxxxx")
        // if (!item) return;
        if (item && eventMap[aim.timestamp]) {
            // console.log("已经存在", eventMap, item.timestamp);
            chart.removeOverlay(eventMap[aim.timestamp]);

            flag = false;
            overlays.map((item: any) => {
                if (item.timestamp == aim.timestamp) {
                    //    chart.removeOverlay(item.id);
                }
            });
        }
        let id = chart.createOverlay({
            name: "event",
            zLevel: 2,
            extendData: {
                data: aim,
                press: false,
                action: !!item ? "more" : aim.char
            },
            points: [
                {
                    timestamp: aim.timestamp,
                    value: aim.high
                }
            ],
            lock: true,
            onRightClick: () => true,
            onClick: (e: any) => {
                console.log("点击---", e);
                let extendData = e.overlay.extendData;
                let list = eventList.filter(i => i.timestamp == aim.timestamp);
                let ary: any[] = [];
                list.forEach(i => {
                    const t = ary.includes((item: any) => item.origin.transactionHash == i.origin.transactionHash);
                    if (!t) {
                        ary.push(i);
                    } else {
                        console.log("重复数据");
                    }
                });
                if (extendData.press) {
                    extendData.press = false;
                    clickEvent(e, ary, false);
                } else {
                    extendData.press = true;
                    // console.log(ary);
                    clickEvent(e, ary, true);
                }
            }
        });

        eventMap[aim.timestamp] = id;

        overlays.push(id);

        eventList.push(aim);
        // console.log("会不会清空呢",eventList)
        return flag;
    }
    function getChartList() {
        return chart && chart.getDataList();
    }
    async function loadBuyData() {
        if (kline.curInterval.name == "S1") return;
        let lastIime = kline.curInterval.name;
        // let item = indicator.getSubByValue("CHAIN_BUY");
        // if((item && item.selected) == false) return;

        let dataList = chart.getDataList();
        let isFirst = dataList.length == 0;

        let ary = isFirst ? kline.list : dataList;

        let type = kline.curInterval.name;
        let startTime = ary[0].timestamp;
        let endTime = ary[ary.length - 1].timestamp;
        let limit = ary.length;

        // 买入净值
        let res: any = await get(URL_BUY_EQUITY_HOME.replace("@", kline.curCoin.tokenAddress || "null"), { type, startTime, endTime, limit }).catch(() => { });
        if (kline.curInterval.name !== lastIime) return;
        let temp = res.data || [];
        temp.forEach((val: any) => {
            let item = ary.find((i: any) => i.timestamp == val.timestamp);
            item && (item.buy = val || {});
        });
        chart.applyNewData(ary);
    }

    async function loadSellData() {
        if (kline.curInterval.name == "S1") return;
        let lastIime = kline.curInterval.name;
        // let item = indicator.getSubByValue("CHAIN_SELL");
        // if((item && item.selected) == false) return;
        let dataList = chart.getDataList();
        let isFirst = dataList.length == 0;
        let ary = isFirst ? kline.list : dataList;
        let type = kline.curInterval.name;
        // let startTime = isFirst ? ary[0].timestamp : ary[ary.length - 30].timestamp;
        let startTime = ary[0].timestamp;
        let endTime = ary[ary.length - 1].timestamp;
        let limit = ary.length;
        // CEX净流出
        let res: any = await get(URL_CAPITAL_EQUITY_HOME.replace("@", kline.curCoin.tokenAddress || "null"), { type, startTime, endTime, limit }).catch(() => { });
        if (kline.curInterval.name !== lastIime) return;
        let temp = res.data || [];
        temp.forEach((val: any) => {
            let item = ary.find((i: any) => i.timestamp == val.timestamp);
            item && (item.sell = val || {});
        });
        chart.applyNewData(ary);
    }

    async function updateBuySell(isFirst = false) {
        if (kline.curInterval.name == "S1") return;
        // let temp = indicator.getSubByValue("CHAIN_VOL");
        // if((temp && temp.selected) == false) return;

        // let ary = isFirst ? kline.list : chart.getDataList();
        try {
            // let type = kline.curInterval.name;
            // let t = isFirst ? ary[0].timestamp : ary[ary.length - 30].timestamp;
            loadBuyData();
            loadSellData();
            checkBSIdx(true);

            // // CEX净流出
            // let res1: any = await get(URL_CAPITAL_EQUITY_HOME.replace("@", kline.curCoin.tokenAddress || "null"), { type: type, startTime: t }).catch(() => { });
            // let outAry = res1.data;

            // // 买入净值
            // let res2: any = await get(URL_BUY_EQUITY_HOME.replace("@", kline.curCoin.tokenAddress || "null"), { type: type, startTime: t }).catch(() => { });
            // let inAry = res2.data;

            // if (outAry.length && inAry.length) {
            //     checkBSIdx(true);
            // }
            // else {
            //     checkBSIdx(false);
            //     return;
            // }

            // outAry.forEach((val: any) => {
            //     let item = ary.find((i: any) => i.timestamp == val.timestamp);
            //     item && (item.sell = val || {});
            // });

            // inAry.forEach((val: any) => {
            //     let item = ary.find((i: any) => i.timestamp == val.timestamp);
            //     item && (item.buy = val || {});
            // });
        } catch (e: any) {
            console.log("load buy sell err", e);
            checkBSIdx(false);
        }

        // chart.applyNewData(ary);
    }

    async function loadMoreBuySell(st: number, ed: number, limit: number) {
        if (!buSellFlag) {
            return;
        }
        buSellFlag = false;
        let ary = chart.getDataList();
        try {
            let type = kline.curInterval.name;
            let res1: any = await get(URL_CAPITAL_EQUITY_HOME.replace("@", kline.curCoin.tokenAddress || "null"), { type: type, startTime: st, endTime: ed, limit }).catch(() => { });
            let outAry = res1.data;
            outAry.forEach((val: any) => {
                let item = ary.find((i: any) => i.timestamp == val.timestamp);
                if (item) {
                    item.sell = val;
                }
            });

            let res2: any = await get(URL_BUY_EQUITY_HOME.replace("@", kline.curCoin.tokenAddress || "null"), { type: type, startTime: st, endTime: ed, limit }).catch(() => { });
            let inAry = res2.data;

            inAry.forEach((val: any) => {
                let item = ary.find((i: any) => i.timestamp == val.timestamp);
                if (item) {
                    item.buy = val;
                }
            });
            // buSellFlag = true
        } catch (e: any) {
            console.log("load buy sell err", e);
            // buSellFlag = true
        } finally {
            setTimeout(() => {
                buSellFlag = true;
            }, 90);
        }

        // chart.applyNewData(ary);
        // chart.scrollToTimestamp(ary[0].timestamp, 0);
        // let t = chart.getDataList();
        // chart.updateData(val);
    }

    function end() {
        if (chart) {
            chart.unsubscribeAction("onScroll", resetDiv);
            // chart.unsubscribeAction("onVisibleRangeChange", addInfo);
            chart.unsubscribeAction("onScroll", resNewDiv);
            chart.unsubscribeAction("onVisibleRangeChange", onVisibleRangeChange);
            changeTimers.forEach(i => window.clearTimeout(i));
            // chart && chart.destroy();
            chart.removeIndicator("candle_pane");
            initSubIndicator = indicator.getSubOpen();
            initMainIndicator = indicator.getMainOpen();
            initSwitch = switchStore.getSwitch();

            dispose(chart);
            console.error("##jsz dispose", cid);
        }
        removeEventListener();
    }

    function reset() {
        end();
        start();
        /*
        let BASE = {maxVol:0,minVol:0,maxPrice:0,minPrice:0};
        setTimeout(() => {
            if (kline.curInterval.name == 'S1') return;
            chart.createIndicator({
                name: "MVOL",
                shortName: "MVOL",
                shouldFormatBigNumber: true,
                calc: function (kLineDataList: any[], indicator: any) {
                    console.log("BASE------", BASE);
                    // let temp1 = kLineDataList.map((kLineData: any) => kLineData.volume);
                    // let max1 = Math.max(...temp1);
                    // let temp2 = kLineDataList.map((kLineData: any) => kLineData.close);
                    // let max2 = Math.max(...temp2);
                    let num = BASE.minPrice;
                    return kLineDataList.map(kLineData => ({ volume: num + ((kLineData.volume - BASE.minVol) / BASE.maxVol * (BASE.maxPrice - BASE.minPrice) * 0.2) }));
                },
                draw: function (param: any) {
                    const { ctx, visibleRange, bounding, indicator, kLineDataList, xAxis, yAxis, barSpace } = param;
                    const { from, to } = visibleRange;
                    const tempAry1 = kLineDataList.slice(from, to);
                    const volumes = tempAry1.map((i: any) => i.volume);
                    const maxVol = Math.max(...volumes);
                    const minVol = Math.min(...volumes);

                    let tempAry2 = kLineDataList.slice(from, to);
                    let ps = tempAry2.map((i: any) => i.high);
                    const maxPrice = Math.max(...ps);

                    tempAry2 = kLineDataList.slice(from, to);
                    ps = tempAry2.map((i: any) => i.low);
                    const minPrice = Math.min(...ps);
                    BASE = { maxVol, minVol, maxPrice, minPrice };
                    return false;
                },
                figures: [
                    {
                        key: "volume",
                        title: "MVOL" + ": ",
                        type: "bar",
                        // baseValue: base,
                        styles: (data: any, indicator: any, defaultStyles: any) => {
                            // console.log(data, "---")
                            const { open, close } = data.current.kLineData;
                            let color = "rgba(45,192,162,0.2)";
                            if (open > close) {
                                color = "rgba(249,40,85,0.2)";
                            }
                            const style = "fill";
                            return { style, color };
                        }
                    }
                ],
                createTooltipDataSource: function (data: any) {
                    let t = formatBigNumber(data.crosshair.kLineData.volume);
                    return {
                        name: "MVOL",
                        values: [{ title: 'VALUE: ', value: { text: t, color: 'rgb(255, 255. 255)' } }]
                    }
                },
                // draw: function (param:any) {
                //     const { ctx, visibleRange, bounding, indicator, kLineDataList, xAxis, yAxis, barSpace } = param;
                //     console.log(param);
                //     const {bar, gapBar, halfBar, halfGapBar} = barSpace;
                //     const {width, height} = bounding;
                //     const {from, to} = visibleRange;
                //     const tempAry = indicator.result.slice(from, to);
                //     const volumes = tempAry.map((i:any)=>i.volume);
                //     const maxVol = Math.max(...volumes);
                //     const minVol = Math.min(...volumes);
                //     ctx.fillStyle = 'rgba(0, 20, 255, .8)';
                //     for(let i = from; i < to; i++){
                //         let h =  1 || indicator.result[i].volume / maxVol * 150;
                //         let x = xAxis.convertTimestampToPixel(kLineDataList[i].timestamp);
                //         let y = height - h;
                //         ctx.fillRect(x - halfBar, y, bar, h);
                //     }

                // }
            }, true, {
                id: "candle_pane",
                dragEnabled: true,
            })

        }, 1000);
        */
    }
    function onVisibleRangeChange(e: any) {
        // console.log("##tom", e)
        if (e.to == chart.getDataList().length) {
            showMoveBtn.value = false;
        } else {
            showMoveBtn.value = true;
        }
    }

    function hideLoading() {
        loading.value = false;
        layout.toggleChartsLoading(false)

    }

    function updateKline(val: any) {
        if (val.symbol !== kline.curCoin.symbol) {
            console.log("切换延迟数据，抛弃");
            return;
        }
        let t = chart.getDataList();
        chart.updateData(val);
        if (val.done) {
            // 更新净买入净流出;
            let temp = indicator.getSubByValue("CHAIN_BUY");
            if (temp && temp.selected) {
                loadBuyData();
            }

            temp = indicator.getSubByValue("CHAIN_SELL");
            if (temp && temp.selected) {
                loadSellData();
            }
        }
    }

    function addEventListener() {
        // chart.subscribeAction("onScroll", resetDiv);
        chart.subscribeAction("onVisibleRangeChange", onVisibleRangeChange);
        // chart.subscribeAction("onVisibleRangeChange", addInfo)
        setTimeout(() => {
            chart.subscribeAction("onVisibleRangeChange", resetDiv);
        }, 500);
        // chart.subscribeAction("onPaneDrag", (e:any)=>{
        //     console.log("drag--------", e)
        // });

        Bus.on(KLINE_CLEAR, (val: any) => {
            loading.value = true;
        });

        Bus.on(KLINE_RESET, hideLoading);

        Bus.on(CONN_SIGNAL, (val: any) => {
            addSignalBS(val);
        });

        Bus.on(CHART_KLINE__LIST, (val: any) => {
            console.warn("val", val);
            // const list = val.sort((a: any, b: any) => (a.timestamp > b.timestamp ? 1 : -1));
            const list = val;
            chart.applyNewData(list);
        });

        Bus.on(CHART_KLINE__ITEM, updateKline);

        Bus.on(CHART_KLINE_SUBSCRIBE_TIME, reset);

        Bus.on(CHART_KLINE_SUBSCRIBE, reset);

        Bus.on(CONN_FLUCTUATION, (val: any) => {
            console.log("链上交易推送", val);
            // if (switchStore.$state.list[0].selected) {
            //     addMark(chart, val);
            // }
        });

        Bus.on(CONN_STABLE_EVENT, addKlineEvent);

        Bus.on(KLINE_RESET_PRICE, calcFix);
        Bus.on(CONN_BIG_AMOUNT, (val: any) => {
            // addMark(chart, val);
        });

        // Bus.on(KLINE_RESET, addHistoryEvent);

        Bus.on(INDICATOR_TOGGLE, (val: any) => {
            // console.log(val, "刚进首页,线不出来");
            if (val.id) {
                console.log(val.id);
                chart.removeIndicator("candle_pane", val.id);
            }
            if (val.value == "FUNDS") {
                if (val.selected) {
                    val.id = createFundRateIndicator(chart);
                    addCloseBtn(chart, val.id, () => {
                        val.selected = false;
                    });
                } else {
                    removeFundRateIndicator(chart);
                }
                return;
            }
            if (val.value == "WAVE") {
                if (val.selected) {
                    val.id = createWaveIndicator(chart);
                    addCloseBtn(chart, val.id, () => {
                        val.selected = false;
                    });
                } else {
                    removeWaveIndicator(chart);
                }
                return;
            }
            // if (val.value == "CHAIN_VOL") {
            //     if (val.selected) {
            //         val.id = createChainVolIndicator(chart);
            //     } else {
            //         removeChainVolIndicator(chart);
            //     }
            //     return;
            // }
            if (val.value == "TREND") {
                toggleTrend(val.selected, chart);
                return;
            }

            if (val.value == "CHAIN_BUY") {
                if (val.selected) {
                    loadBuyData();
                }
            }
            if (val.value == "CHAIN_SELL") {
                if (val.selected) {
                    loadSellData();
                }
            }

            if (val.selected) {
                if (val.main) {
                    val.id = val.value;
                    chart.createIndicator(val.value, true, { id: "candle_pane" });
                    // console.log(val.id, val.value, "  val.id   val.id   val.id   val.id   val.id ")
                } else {
                    val.id = chart.createIndicator({ name: val.value, extendData: { jsz: "jsz_" + val.value } }, false);
                    addCloseBtn(chart, val.id, () => {
                        val.selected = false;
                    });
                }
            } else {
                chart.removeIndicator(val.id);
            }
        });
        // 判断是否最大值
        function isMax(num: number, array1: Array<number>, array2: Array<number>): boolean {
            if (array1.length === 0 || array2.length === 0) {
                throw new Error("数组为空");
            }
            const max1 = Math.max(...array1);
            const max2 = Math.max(...array2);

            return num > max1 && num > max2;
        }
        function isMin(num: number, array1: Array<number>, array2: Array<number>): boolean {
            if (array1.length === 0 || array2.length === 0) {
                throw new Error("数组为空");
            }
            const min1 = Math.min(...array1);
            const min2 = Math.min(...array2);

            return num < min1 && num < min2;
        }
        // 开关k线上的文本框 趋势信号
        Bus.on(SWITCH_TOGGLE, (val: any) => {
            console.log(val, switchStore.$state.list[0].selected, switchStore.$state.list, "点击开关");

            if (val.value == "WG" && val.selected) {
                val.id = 1;
                chart.setStyles({
                    grid: { show: true }
                });
                return;
            } else if (val.value == "WG" && !val.selected) {
                // val.selected = false
                chart.setStyles({
                    grid: { show: false }
                });
                return;
            }
            if (val.selected) {
                if (val.value == "action") {
                    activity.loadHistory(kline.curCoin.tokenAddress).then(() => {
                        // console.log("加载历史记录", res);
                        addHistoryEvent();
                    });
                } else if (val.value == "signal") {
                    //买入卖出信号
                    // signal.loadHistory(kline.curCoin.symbol, kline.curInterval.name).then(() => {

                    // });
                    chart.removeOverlay({ name: "signal" });
                    let klineData = chart.getDataList();
                    console.log(kline.list, "  signal.list  signal.list  signal.list");
                    let data = caclLine(klineData);
                    let flag = 0;
                    let temp = 1;

                    data.map((item: any, index: any) => {
                        // if (item.trend1 && item.trend2) {

                        // }
                        if (item.trend1 > item.trend2) {
                            item.direction = 1;
                            // console.log(item.trend1 > item.trend2, item.trend1, item.trend2, "赋值1", item)
                        } else {
                            item.direction = -1;
                            // console.log(item.trend1 > item.trend2, item.trend1, item.trend2, "赋值-1", item)
                        }
                        // if (item.timestamp == '1696118400000') {
                        //     console.log(item)
                        // }
                    });
                    data.map((item: any, index: any) => {
                        // if (item.trend1 && item.trend2) {

                        // }
                        // let flag1 = item.direction == 1
                        // let flag2 = item.direction == -1

                        // let flag3 = item.open < item.close
                        // let flag4 = item.low < item.trend2
                        // let flag5 = item.high > item.trend2
                        // let flag6 = item.open > item.close
                        let buyArr = [
                            {
                                flag: item.direction == 1,
                                use: true
                            },
                            {
                                flag: item.close < item.trend2,
                                use: true
                            },
                            {
                                flag: item.open < item.close,
                                use: true
                            }
                        ];
                        let sellArr = [
                            {
                                flag: item.direction == -1,
                                use: true
                            },
                            {
                                flag: item.close > item.trend2,
                                use: true
                            },
                            {
                                flag: item.open > item.close,
                                use: true
                            }
                        ];

                        let buyUse = buyArr.filter(item => item.use);
                        let buyNum = buyUse.filter(item => item.flag);
                        let sellUse = sellArr.filter(item => item.use);
                        let sellNum = sellUse.filter(item => item.flag);
                        if (buyUse.length == buyNum.length) {
                            if (temp) {
                                item.signal = 1;
                                temp = 0;
                            }
                        } else if (sellNum.length == sellUse.length) {
                            if (temp) {
                                item.signal = -1;
                                temp = 0;
                            }
                        } else {
                            if (item.direction == 1 && item.close > item.trend2) {
                                temp = 1;
                            } else if (item.direction == -1 && item.close < item.trend2) {
                                temp = 1;
                            }
                        }
                    });
                    data.forEach((i: any) => {
                        let id = addSignalBSCopy(i);
                        overlays.push(id);
                    });
                } else if (val.value == 'StockSignal') {
                    chart.removeOverlay({ name: "StockSignal" });
                    let data = chart.getDataList();
                    // let data = caclLine(klineData);
                    let len = 15
                    let rightLen = 8
                    data.map((item: any, index: any) => {
                        if (index < len || data.length - index - 1 < rightLen) {
                            return
                        }
                        let arr = data.slice(index - len, index)
                        let arr2 = data.slice(index + 1, index + 1 + rightLen)
                        if (isMax(item.high, arr.map((x: any) => x.high), arr2.map((x: any) => x.high))) {
                            item.shockSignal = -1
                            // console.log(item, new Date(item.timestamp))
                        } else if (isMin(item.low, arr.map((x: any) => x.low), arr2.map((x: any) => x.low))) {
                            item.shockSignal = 1
                            // console.log(item, new Date(item.timestamp))
                        }
                    });
                    data.forEach((i: any) => {
                        let id = addSignalShock(i);
                        overlays.push(id);
                    });
                }
            } else {
                eventMap = {};
                overlays.splice(0);
                eventList = [];
                if (val.value == "action") {
                    chart.removeOverlay({ name: "action" });
                    chart.removeOverlay({ name: "event" });
                } else {
                    chart.removeOverlay({ name: val.value });
                }
            }
        });

        window.addEventListener("resize", resizeView);
    }

    function caclLine(dataList: any) {
        let closeSum = 0;
        const emaValues: number[] = [];
        let figures = ["fast1", "fast2", "fast3", "trend1", "trend2"];
        let params = [5, 10, 15, 90, 144];
        const ema: any = {};

        let dataArr = dataList.map((kLineData: any, i: number) => {
            const close = kLineData.close;
            closeSum += close;
            params.forEach((p: number, index: number) => {
                if (i >= p - 1) {
                    if (i > p - 1) {
                        emaValues[index] = (2 * close + (p - 1) * emaValues[index]) / (p + 1);
                    } else {
                        emaValues[index] = closeSum / p;
                    }
                    // console.log(emaValues[index])
                    kLineData[figures[index]] = emaValues[index] ? emaValues[index] : 0;
                }
            });
            // kLineData.trend1=ema['ema18']

            // kLineData.trend2=ema['ema19']
        });
        // console.log(dataList,"132312")
        return dataList;
    }

    function addHistoryEvent() {
        // console.log("循环开始", activity, activity.eventList)
        // console.log("addHistoryEvent --------------------", activity.eventList, chart.getDataList().length);
        activity.eventList.forEach(val => {
            // console.log("循环", val)
            addKlineEvent(val);
        });
    }

    function addKlineEvent(val: any) {
        // console.log("###ttt", val,index);
        // if(Math.abs(val.outAmount)< 10){
        //     console.log("###ttt 没有过滤", val);
        // }
        // let min = 10000;
        //过滤条件
        // if (Math.abs(val.outusdt) > min) {
        // if (switchStore.$state.list[0].selected) {
        //     addMark(chart, val);
        // }
        // }
    }

    function resizeView() {
        if (chart) {
            console.log("--------resize", chart);
            chart.resize();
            resizeChart();
        }

        if (newspot.value) {
            newspot.value.style.visibility = "hidden";
        }
        if (move.value) {
            move.value.style.visibility = "hidden";
        }

        setTimeout(() => {
            resetDiv();
            resNewDiv();
            if (newspot.value) {
                newspot.value.style.visibility = "visible";
            }
            if (move.value) {
                move.value.style.visibility = "visible";
            }
        }, 300);
    }

    function removeEventListener() {
        Bus.off(KLINE_CLEAR);
        Bus.off(KLINE_RESET, hideLoading);
        Bus.off(CONN_SIGNAL);
        Bus.off(CHART_KLINE__LIST);
        Bus.off(CHART_KLINE__ITEM, updateKline);
        Bus.off(CHART_KLINE_SUBSCRIBE_TIME, reset);
        Bus.off(CHART_KLINE_SUBSCRIBE, reset);
        Bus.off(CONN_FLUCTUATION);
        // Bus.off(CONN_BIG_AMOUNT);
        Bus.off(INDICATOR_TREND);
        Bus.off(INDICATOR_TOGGLE);
        Bus.off(CONN_STABLE_EVENT, addKlineEvent);
        Bus.off(SWITCH_TOGGLE);
        Bus.off(KLINE_RESET_PRICE, calcFix);

        // Bus.off(KLINE_RESET, addHistoryEvent);

        window.removeEventListener("resize", resizeView);
    }

    function toggleTrend(val: boolean, chart: any) {
        let ary = chart.getDataList();
        if (val) {
            ary.forEach((i: any) => {
                if (i.trend == 0) {
                    i.color = "#fcc235";
                } else if (i.trend == 1) {
                    i.color = "#0dcb81";
                } else if (i.trend == -1) {
                    i.color = "#f6475d";
                } else {
                    i.color = "#909090";
                }
            });
        } else {
            ary.forEach((i: any) => delete i.color);
        }
        chart.applyNewData(ary);
    }

    function addSignalBS(pot: any) {
        console.log("addSignalBS", pot);
        if (!pot.low) {
            // const ary = chart.getDataList();
            const aim = getNearTime(chart.getDataList(), pot);
            if (!aim) {
                console.log("找不到买卖时间点");
                return null;
            }
            pot.high = aim.high;
            pot.low = aim.low;
            pot.visible = true;
        }

        if (pot.action == "deposit") {
            //充值 红
            pot.color = "#F6475D";
        } else if (pot.action == "withdraw") {
            //提现 绿
            pot.color = "#0DCB81";
        }

        let direction = Number(pot.direction);
        return chart.createOverlay({
            name: "signal",
            extendData: pot,
            points: [
                {
                    timestamp: pot.timestamp,
                    value: direction > 0 ? pot.low : pot.high
                }
            ],
            lock: true,
            onClick: (e: any) => {
                console.log(e);
            }
            // onMouseEnter: onMouseEnter,
            // onMouseLeave: onMouseLeave
        });
    }
    // 震荡信号
    function addSignalShock(pot: any) {
        // console.log("addSignalBS", pot);
        // if (!pot.low) {
        //     // const ary = chart.getDataList();
        //     const aim = getNearTime(chart.getDataList(), pot);
        //     if (!aim) {
        //         console.log("找不到买卖时间点");
        //         return null;
        //     }
        //     pot.high = aim.high;
        //     pot.low = aim.low;
        //     pot.visible = true;
        // }

        // if (pot.action == "deposit") {
        //     //充值 红
        //     pot.color = "#F6475D";
        // } else if (pot.action == "withdraw") {
        //     //提现 绿
        //     pot.color = "#0DCB81";
        // }
        if (!pot.shockSignal) {
            return;
        }
        let direction = Number(pot.shockSignal);
        return chart.createOverlay({
            name: "StockSignal",
            extendData: pot,
            points: [
                {
                    timestamp: pot.timestamp,
                    value: direction > 0 ? pot.low : pot.high
                }
            ],
            lock: true,
            onClick: (e: any) => {
                console.log(e);
            }
            // onMouseEnter: onMouseEnter,
            // onMouseLeave: onMouseLeave
        });
    }

    // 趋势信号
    function addSignalBSCopy(pot: any) {
        // console.log("addSignalBS", pot);
        // if (!pot.low) {
        //     // const ary = chart.getDataList();
        //     const aim = getNearTime(chart.getDataList(), pot);
        //     if (!aim) {
        //         console.log("找不到买卖时间点");
        //         return null;
        //     }
        //     pot.high = aim.high;
        //     pot.low = aim.low;
        //     pot.visible = true;
        // }

        // if (pot.action == "deposit") {
        //     //充值 红
        //     pot.color = "#F6475D";
        // } else if (pot.action == "withdraw") {
        //     //提现 绿
        //     pot.color = "#0DCB81";
        // }
        if (!pot.signal) {
            return;
        }
        let direction = Number(pot.signal);
        return chart.createOverlay({
            name: "signal",
            extendData: pot,
            points: [
                {
                    timestamp: pot.timestamp,
                    value: direction > 0 ? pot.low : pot.high
                }
            ],
            lock: true,
            onClick: (e: any) => {
                console.log(e);
            }
            // onMouseEnter: onMouseEnter,
            // onMouseLeave: onMouseLeave
        });
    }

    function addPot(pot: any) {
        if (!pot.low) {
            // const ary = chart.getDataList();
            const aim = getNearData(chart.getDataList(), pot);
            if (!aim) {
                console.log("none signal=======");
                return null;
            }
            pot.high = aim.high;
            pot.low = aim.low;
            pot.visible = true;
            // let x = chart.convertToPixel({timestamp: pot.timestamp});
            // let y = chart.convertToPixel({value: pot.high}, {paneId: "candle_pane"});
            // console.log(x, y, 'x, y')
        }

        if (pot.action == "deposit") {
            //充值 红
            pot.color = "#F6475D";
        } else if (pot.action == "withdraw") {
            //提现 绿
            pot.color = "#0DCB81";
        }

        let direction = Number(pot.direction);

        signal.addItem(pot);

        // console.log("pop high", pot.high)
        return chart.createOverlay({
            name: "pot",
            extendData: pot,
            points: [
                {
                    timestamp: pot.timestamp,
                    value: direction > 0 ? pot.low : pot.high
                }
            ],
            lock: true,
            onClick: (e: any) => {
                console.log(e);
            },
            onMouseEnter: (e: any) => {
                console.log(e, "enter pot");
                const obj = e.overlay.extendData;
                // console.log(e, "enter", obj)
                const up = obj.outAmount > 0 ? 1 : 0;
                if (obj.type) {
                    let address = obj.fromTag || obj.address;
                    let toAddress = obj.toTag || obj.toAddress;
                    address = maskHash(address);
                    toAddress = maskHash(toAddress);

                    let outAmount = obj.outAmount ? formatBigNumber(Math.abs(obj.outAmount)) : 0;
                    let outusdt = formatBigNumber(obj.outusdt);
                    if (obj.type == "swap") {
                        // let inAmount = obj.inAmount ? formatBigNumber(Math.abs(obj.inAmount)) : 0;
                        // let outAmount = obj.outAmount ? formatBigNumber(Math.abs(obj.outAmount)) : 0;
                        let tip0 = `大額成交`;
                        let tip1 = `${outAmount}#${obj.outSymbol} ($${outusdt})`;
                        let tip2 = `從${address}到${toAddress}`;
                        let tip3 = `${formatTimestamp(obj.timestamp)}`;
                        toolTips.value = [tip0, tip1, tip2, tip3];
                    } else {
                        let tip0 = `大額轉賬`;
                        let tip1 = `${outAmount}#${obj.outSymbol} ($${outusdt})`;
                        let tip2 = `從${address}到${toAddress}`;
                        let tip3 = `${formatTimestamp(obj.timestamp)}`;
                        toolTips.value = [tip0, tip1, tip2, tip3];
                    }
                } else {
                    toolTips.value = [];
                    toolTips.value = [obj.name, obj.date];
                }
            },
            onMouseLeave: (e: any) => {
                toolTips.value = [];
            }
        });
    }

    function addMark(chart: any, val: any, immediately = false) {
        let ary = chart.getDataList();
        if (ary.length == 0) {
            ary = kline.list;
        }

        // console.log("----", kline.list);
        const aim = getNearData(ary, val);
        if (!aim) {
            // console.log("no find time event", new Date(val.timestamp));
            return;
        }
        let title = "";
        let up = false;
        val.high = aim.high;
        val.timestamp = aim.timestamp;

        // if (immediately) {
        //     let id = addPot(val);
        //     overlays.push(id);
        //     return;
        // }

        let act = "in";

        if (val.type == "transfer") {
            if (val.action == "withdraw") {
                //提现
                title = "withdraw";
                act = "out";
                up = true;
            } else if (val.action == "deposit") {
                //充值
                title = "deposit";
                act = "out";
                up = false;
            }
            //普通转账
            else {
                title = "transfer";
                act = "out";
                up = false;
            }
        } else {
            if (val.action == "buy") {
                //买
                title = "buy";
                act = "in";
                up = true;
            } else if (val.action == "sell") {
                //卖
                title = "sell";
                act = "out";
                up = false;
            } else {
                title = "sell";
                act = "out";
                up = false;
            }
        }

        //买 in
        //卖 out
        let gg: any = addEvent({ ...aim, origin: val, char: title[0] });
        if (!gg) {
            return;
        }
        // console.log("开始绘制", aim)
        let fg = chart.createOverlay({
            name: "action",
            zLevel: 999,
            extendData: {
                title: title,
                sub: `${formatBigNumber(val[act + "Amount"])}`, //(${val[act + "Symbol"]})
                up: up,
                data: aim,
                origin: val
            },
            points: [
                {
                    timestamp: aim.timestamp,
                    value: aim.high
                }
            ],
            lock: true,
            onClick: (e: any) => {
                console.log(312313131312)
                console.log(e);

                console.log("点击---", e);
                let extendData = e.overlay.extendData;
                let list = eventList.filter(i => i.timestamp == aim.timestamp);
                let ary: any[] = [];
                list.forEach(i => {
                    const t = ary.includes((item: any) => item.origin.transactionHash == i.origin.transactionHash);
                    if (!t) {
                        ary.push(i);
                    } else {
                        console.log("重复数据");
                    }
                });
                if (extendData.press) {
                    extendData.press = false;
                    clickEvent(e, ary, false);
                } else {
                    extendData.press = true;
                    // console.log(ary);
                    clickEvent(e, ary, true);
                }


                // chart.removeOverlay(fg)
            },
            onMouseEnter: (e: any) => {
                // console.log(e, "enter")
            },
            onMouseLeave: (e: any) => {
                // console.log(e, "leave")
            }
        });
        overlays.push(fg);

        // let tid = setTimeout(() => {
        //     chart.removeOverlay(fg);
        //     let id = addPot(val);
        //     overlays.push(id);

        //     let n = changeTimers.indexOf(tid);
        //     if (n != -1) {
        //         changeTimers.splice(n, 1);
        //     }
        // }, 60000);

        // changeTimers.push(tid);
    }

    function onMove() {
        const ary = chart.getDataList();
        // console.log(ary, "move");
        chart.scrollToTimestamp(ary[ary.length - 1].timestamp, 900);
    }
    function resNewDiv() {
        let t: any = document.getElementById(cid)?.querySelector("canvas");
        if (t && newspot.value) {
            newspot.value.style.left = t.clientWidth - 78 + "px";
            newspot.value.style.top = t.clientHeight - 40 + "px";
        }
    }
    function resetDiv(data: any = null) {
        // console.log("scroll====", data)
        let t: any = document.getElementById(cid)?.querySelector("canvas");
        if (t && move.value) {
            move.value.style.left = t.clientWidth - 40 + "px";
            move.value.style.top = t.clientHeight - 40 + "px";
        }
    }
    function getYAxisWidth() {
        let num = 0;
        let temp: any = document.getElementById(cid)?.querySelectorAll("canvas");
        if (temp) {
            [...temp].forEach(i => {
                if (i.width / i.height < 0.5) {
                    num = i.width;
                }
            });
        }
        return num;
    }

    function checkInit() {
        return !!chart;
    }

    function resizeChart() {
        setTimeout(() => {
            chart && chart.resize();
        }, 300);

        setTimeout(() => {
            chart && chart.executeAction("onZoom");
        }, 900);

        setTimeout(() => {
            chart && chart.executeAction("onScroll");
        }, 1200);
    }

    function addInfo(pot: any) {
        if (infoId.value) {
            chart.removeIndicator("candle_pane", infoId.value);
        }
        // console.error("addInfo pot", pot);
        infoId.value = chart.createIndicator(
            {
                name: "INFORMATION",

                draw: (param: any) => {
                    let { xAxis, kLineDataList, ctx } = param;
                    const width = 20;
                    const height = 20;
                    let last = kLineDataList[kLineDataList.length - 1];
                    // let x = xAxis.convertTimestampToPixel(last.timestamp);
                    // let y = ctx.canvas.height / window.devicePixelRatio - height / 2 - 30;
                    let x = ctx.canvas.width - 30;
                    let y = ctx.canvas.height / window.devicePixelRatio - height / 2 - 70;
                    // console.log('改变poit&&&&&&&&&&&&&', x, y)
                    let r = width / 2;
                    ctx.setLineDash([]);
                    ctx.strokeStyle = "#7E7467";
                    ctx.fillStyle = "rgba(0, 0, 0, 0.1)";
                    ctx.beginPath();
                    ctx.arc(x, y, r, 0, (360 * Math.PI) / 180, false);
                    // ctx.stroke();
                    ctx.fill();

                    pot.x = x;
                    pot.y = y;
                    pot.opacity = x > ctx.canvas.width - 20 ? 0.1 : 1;
                    return false;
                }
            },
            true,
            { id: "candle_pane", axisOptions: { scrollZoomEnabled: false } }
        );
        // console.log('addInfo pot', infoId.value)
        // console.error("addInfo pot tid", infoId.value);
    }

    return { loading, toolTips, start, end, reset, resizeView, onMove, checkInit, getYAxisWidth, resizeChart, getChartList, showMoveBtn, infoViewData, newspot };
};

const calcVRVP = function (candles: any[], count: number) {
    let lower = Math.min(...candles.map(x => x.low));
    let higher = Math.max(...candles.map(x => x.high));
    // const count = 30;
    const ary = [];
    const priceStep = (higher - lower) / count;
    for (let i = 0; i < count; i++) {
        const sp = i * priceStep + lower;
        const ep = sp + priceStep;
        let item = { t: 0, b: 0, s: 0, p: 0 };
        candles.forEach(kline => {
            let n = (kline.open + kline.close) / 2;
            if (n >= sp && n < ep) {
                item.t += kline.volume;
                if (kline.open > kline.close) {
                    item.b += kline.volume;
                } else {
                    item.s += kline.volume;
                }
                item.p = sp;
            }
        });
        ary.push(item);
    }
    return ary;

    // 统计价格区间内的成交量
    // const volumeProfile = _.reduce(
    // 	candles,
    // 	(result, kline) => {
    // 		const price = (kline.open + kline.close) / 2; // 使用开盘价和收盘价的平均值作为价格
    // 		if (price >= priceRange[0] && price <= priceRange[1]) {
    // 			const volume = kline.volume;
    // 			result[price] = (result[price] || 0) + volume;
    // 		}
    // 		return result;
    // 	},
    // 	{}
    // );
    // vrvpDict.value = volumeProfile;
    // console.log('vrvp', volumeProfile)
};
